package ch.subgate.pongwars;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;

import java.io.IOException;
import java.util.UUID;

public class ConnectThread extends Thread {
    private final BluetoothSocket mSocket;
    private final GameActivity mActivity;

    public ConnectThread(String addr, GameActivity activity) {
        BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(addr);
        // Use a temporary object that is later assigned to mmSocket,
        // because mmSocket is final
        BluetoothSocket tmp = null;
        mActivity = activity;

        // Get a BluetoothSocket to connect with the given BluetoothDevice
        try {
            // MY_UUID is the app's UUID string, also used by the server code
            tmp = device.createRfcommSocketToServiceRecord(UUID.fromString(Constants.MY_UUID));
        } catch (Exception e) {
        }
        mSocket = tmp;
    }

    public void run() {
        try {
            // Connect the device through the socket. This will block
            // until it succeeds or throws an exception
            mSocket.connect();
        } catch (IOException e1) {
            // Unable to connect; close the socket and get out
            try {
                mSocket.close();
            } catch (IOException e2) {
            }
            return;
        }

        // Do work to manage the connection (in a separate thread)
        mActivity.manageConnectedSocket(mSocket);
    }

    /** Will cancel an in-progress connection, and close the socket */
    public void cancel() {
        try {
            mSocket.close();
        } catch (IOException e) {
        }
    }
}